import styles from './index.module.scss'
import { useState, useRef, useEffect } from 'react'
import Input from './input'
import { loginIn, sendCode } from '@/api/login'
import dayjs from 'dayjs'
import { cncryptionCipher } from './encode'
import Button from '../button'
import { loginSuccessReport } from '@/utils/report'
import { injectScript } from '@/utils/utils'
import { useRouter } from 'next/router'
import Loading from '@c/fetch-loading'
import cm from 'classnames'

const reportData = data => {
  const { email, expireTime } = data
  const lastTime = dayjs(expireTime * 1000).diff(new Date())
  loginSuccessReport({
    email,
    user_is_vip: lastTime > 0 ? 'true' : 'false',
    login_time: new Date().toLocaleString()
  })
}

// 获取易盾token
const getYiDunToken = async () => {
  await injectScript('/js/yidun-web.js', 'yidun')
  const neg = createNEGuardian({ appId: 'YD00766955874482', timeout: 10000 })
  const result = await neg.getToken()
  return result?.token || ''
}

const Index = props => {
  const { email: medium, setType, setEmail } = props
  const submitRef = useRef(null)
  const inputRef = useRef(null)
  const [pwdErr, setPwdErr] = useState(false)
  const [password, setPwd] = useState('')
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const login = async () => {
    if (loading) {
      return
    }
    if (!password) {
      setPwdErr(true)
      return
    }
    const ydtoken = await getYiDunToken()
    const MuId =  localStorage.getItem('MuId')
    const res = await loginIn({ medium, password: cncryptionCipher(password), ydtoken },{headers:{MuId:MuId ? MuId: undefined}})
    setLoading(true)
    if (res.code) {
      setPwdErr(true)
      setLoading(false)
    } else {
      setPwdErr(false)
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('email', medium)
      reportData(res.data.user)
      setLoading(false)
      setTimeout(() => {
        window.location.reload()
      }, 10)
    }
  }

  // 忘记密码
  const resetPwd = () => {
    sendCode(medium)
    setType('reset_verify')
  }

  const preview = () => {
    setType('enter_email')
    setEmail('')
  }

  useEffect(() => {
    const enterClick = e => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    inputRef.current.focus()
    window.addEventListener('keydown', enterClick)
    return () => {
      window.removeEventListener('keydown', enterClick)
    }
  }, [])

  return (
    <div className={styles.checkPwd}>
      <p className={styles.email}>{medium}</p>
      <p className={styles.noEmail} onClick={preview}>
        不是你的邮箱?
      </p>
      <Input
        placeholder="请输入密码"
        ref={inputRef}
        type="password"
        className={styles.pwd}
        onChange={data => setPwd(data)}
      />
      <p className={styles.error}>
        <span>{pwdErr ? '密码错误，请重新输入' : ''}</span>
        <span onClick={resetPwd}>忘记密码？</span>
      </p>
      <Button
        hover="opacity"
        ref={submitRef}
        onClick={login}
        className={cm(styles.btn, loading ? styles.btnLoading : '')}
      >
        {loading && <Loading width={10} className="mr-2" />}
        {loading ? '登录中...' : '登录'}
      </Button>
    </div>
  )
}

export default Index
